﻿Imports System.Net.Mail
Imports System.Net

<HandleError()> _
Public Class AdminController
    Inherits System.Web.Mvc.Controller

    Private adminRepo As AdminRepository
    Private usersEmailed As Integer = 0

    <Authorize()> _
    Function Index() As ActionResult
        If Not User.IsInRole("admin") Then
            Return View("NotAuthorized")
        End If

        Return View("Index")
    End Function

    <Authorize()> _
    Function AllUsers() As ActionResult
        If Not User.IsInRole("admin") Then
            Return View("NotAuthorized")
        End If

        adminRepo = New AdminRepository(User.IsInRole("admin"))

        Dim userRepo As New UserRepository()
        adminRepo.ListOfPicks = userRepo.GetListOfUserPicks()

        Return View("AllUsers", adminRepo)
    End Function

    <Authorize()> _
    Function SendEmail() As ActionResult
        If Not User.IsInRole("admin") Then
            Return View("NotAuthorized")
        End If

        Return View()
    End Function
    
    <AcceptVerbs(HttpVerbs.Post), Authorize()> _
    Function SendEmail(subject As String, body As String) As ActionResult

        Dim userCount As Integer = 0
        Try

            Dim mail = New MailMessage("ncaasurvivorpool@gmail.com", "ncaasurvivorpool@gmail.com")
            mail.Subject = subject
            mail.Body = body

            Dim users = Membership.GetAllUsers()
            Dim distinctList As New ArrayList()

            For Each user As MembershipUser In users
                If user.Email IsNot Nothing AndAlso user.Email <> "" Then
                    If Not distinctList.Contains(user.Email) AndAlso EmailAddressCheck(user.Email) Then
                        mail.Bcc.Add(user.Email)
                        distinctList.Add(user.Email)
                        userCount += 1
                    End If
                End If
            Next

            'Dim mail = ConfigurationSettings.AppSettings["MailServer"]
            Dim mailServer = ConfigurationManager.AppSettings("MailServer").ToString()

            Using smtp As New SmtpClient(mailServer)
                smtp.Send(mail)
            End Using

            If Session("usersEmailed") Is Nothing Then
                Session.Add("usersEmailed", userCount)
            Else
                Session("usersEmailed") = userCount
            End If

            Return RedirectToAction("SendEmailSuccess")
        Catch ex As Exception
            ModelState.AddModelError("_FORM", ex.ToString())
            Return View()
        End Try
    End Function

    Function EmailAddressCheck(ByVal emailAddress As String) As Boolean
        Const pattern As String = "^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"
        Dim emailAddressMatch As Match = Regex.Match(emailAddress, pattern)
        Return emailAddressMatch.Success
    End Function

    Function SendEmailSuccess() As ActionResult
        ViewData("UsersEmailed") = Session("usersEmailed").ToString
        Return View()
    End Function


    <Authorize()> _
    Function Winners() As ActionResult
        If Not User.IsInRole("admin") Then
            Return View("NotAuthorized")
        End If

        Dim displayRound = GlobalController.FindCurrentRound()
        ViewData("CurrentRound") = displayRound
        ViewData("MainMsg") = ""
        Return View("Winners", GetListOfTeams(displayRound))
    End Function

    Private Function GetListOfTeams(ByVal round As Integer) As List(Of TeamObj)
        Dim teamRepo As New TeamRepository()
        Return teamRepo.FindAllTeamsForSpecificRound(GlobalVars.curYear, round)
    End Function

    <AcceptVerbs(HttpVerbs.Post), Authorize()> _
    Function Winners(ByVal formValues As FormCollection) As ActionResult
        Dim displayRound = 1
        Try
            Dim teamRepo As New TeamRepository()
            displayRound = GlobalController.FindCurrentRound()

            Using mySession = Persister.OpenSession()
                Using myTrans = mySession.Transaction
                    myTrans.Begin()
                    For i As Integer = 0 To formValues.Count - 1
                        Dim tmpTeam = formValues.Keys(i)
                        Dim tmpResult = formValues(i)

                        teamRepo.SaveTeamResult(mySession, displayRound, tmpTeam, tmpResult)
                    Next
                    myTrans.Commit()
                End Using
            End Using

            'Dim picks = formValues("Pick").Split(",")
            'Dim teams = formValues("Team").Split(",")

            'If id > 1 Then
            '    'Check for existing picks
            '    Dim myPicks = picksRepo.FindAllPicksPerUser(User.Identity.Name)
            '    For i As Integer = 0 To picks.Count - 1
            '        Dim tmpTeamId = teams(i)
            '        For Each tmpPick In myPicks
            '            If tmpPick.Team IsNot Nothing AndAlso tmpPick.Team.TeamId = tmpTeamId AndAlso tmpPick.BracketRound < id Then
            '                'This team has already been chosen by this user in a previous round
            '                ViewData("ErrorMsg") = String.Format("You have previouslry chosen {0}.  Please pick a different team.", tmpPick.Team.TeamName)
            '                LoadViewData(id)
            '                Return View("Edit", picksRepo.FindUserPicksPerRound(User.Identity.Name, id))
            '            End If
            '        Next
            '    Next
            'End If

            'For i As Integer = 0 To picks.Count - 1
            '    picksRepo.SavePickInfo(picks(i), teams(i))
            'Next

            sysLog.Debug("Winners changed by " & User.Identity.Name)

            ViewData("CurrentRound") = displayRound
            ViewData("MainMsg") = "Your changes have been saved"
            Return View("Winners", GetListOfTeams(displayRound))
        Catch ex As Exception
            sysLog.Error("Selecting winners --> " & ex.ToString())
            ViewData("CurrentRound") = displayRound
            ViewData("MainMsg") = String.Concat("Error occurred: ", ex.Message)
            Return View("Winners", GetListOfTeams(displayRound))
        End Try
    End Function
End Class
